package com.ztgf.commodity.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityComboRelationMapper;
import com.ztgf.commodity.models.bo.CommodityComboRelationSaveBO;
import com.ztgf.commodity.models.dto.CommodityComboRelationDTO;
import com.ztgf.commodity.models.dto.CommoditySpecificationRelationDTO;
import com.ztgf.commodity.models.service.ICommodityComboRelationService;
import com.ztgf.commodity.models.vo.CommodityComboRelationVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品套餐关系表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-15 14:09:15
 */
@DubboService
public class CommodityComboRelationServiceImpl extends ServiceImpl<CommodityComboRelationMapper, CommodityComboRelationDTO> implements ICommodityComboRelationService {

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(CommodityComboRelationSaveBO saveBO) {
        CommodityComboRelationDTO dto = new CommodityComboRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 根据套餐id和商品id查询
     *
     * @param comboId
     * @param goodsId
     * @return
     */
    @Override
    public CommodityComboRelationDTO selectByCommodityAndComIds(Long comboId, Long goodsId) {
        return baseMapper.selectByCommodityAndAttrIds(comboId, goodsId);
    }

    @Override
    public boolean deleteByCommodityId(Long id) {
        Wrapper<CommodityComboRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", id);
        List<CommodityComboRelationDTO> list = this.selectList(wrapper);
        List<Long> ids = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (CommodityComboRelationDTO dto : list) {
                ids.add(dto.getId());
            }
            return this.deleteBatchIds(ids);
        }
        return false;
    }

    @Override
    public CommodityComboRelationVO getByGoodsIdAndComboId(Long goodsId, Long comboId) {
        CommodityComboRelationVO vo = baseMapper.getByGoodsIdAndComboId(goodsId, comboId);
        if (vo != null) {
            return vo;
        } else {
            CommodityComboRelationVO relationVO = new CommodityComboRelationVO();
            relationVO.setInventoryNumber(0);
            return relationVO;
        }
    }
}
